<template>
    <ve-table 
        fixed-header
        :style="{'word-break':'break-word'}"
        :max-height="tableHeight"
        :columns="columns"
        :scroll-width="600"
        :table-data="tableList"
        rowKeyFieldName="number"
        :eventCustomOption="eventCustomOption"
        :rowStyleOption="rowStyleOption"
        :checkbox-option="checkboxOption"
        :sort-option="sortOption"
        :contextmenu-body-option="showRoleCheck ? contextmenuBodyOptionMain : null"
        :virtual-scroll-option="!isOverview && !isEnv ? virtualScrollMain : null"
        border-y
        border-x 
    />

</template>
<script>
export default ({
    name:'TableView',
    props:{
        tableHeight:{
            type:[Number,String],
            default:200
        },
        tableComPs:{
            type:Array,
            default:()=>{
                return []
            }
        },
        tableList:{
            type:Array,
            default:()=>{
                return []
            }
        },
        isOverview:{
            type:Boolean,
            default:false
        },
        isEnv:{
            type:Boolean,
            default:false
        },
        enableVirtualScroll: {
            type: Boolean,
            default: false
        },
        showRoleCheck:{
            type:Number,
            default:0
        },
        isChartFilter:{
            type:Boolean,
            default:false
        }
    },
    data() {
        return{
            timer: null,
            // 行样式配置
            rowStyleOption: {
                clickHighlight: false,
                hoverHighlight: true,
            },
            eventCustomOption:{
                bodyCellEvents:({row,column,rowIndex})=>{
                    return {
                        click: (event) => {
                            this.$emit('preview',row,column)
                        },
                    }
                },
            },
            sortOption: {
              sortChange: (params) => {
                  this.sortChange(params);
              },
            }, 
            checkedDataList:[],
            checkboxOption: {
              selectedRowKeys: [],
              // 行选择改变事件
              selectedRowChange: ({ row, isSelected, selectedRowKeys }) => {
                  this.checkboxOption.selectedRowKeys = selectedRowKeys;
                  if(isSelected){
                      this.checkedDataList.push({
                          id:row.id,
                          code_id:row.codE_ID,
                          status:''
                      })
                  }else{
                        this.isAllSelected = false;
                        const index = this.checkedDataList.findIndex(item => item.id === row.id)
                        if (index > -1) {
                        this.checkedDataList.splice(index, 1)
                        }
                  }
              },
              // 全选改变事件
              selectedAllChange: ({ isSelected, selectedRowKeys }) => {
                    this.isAllSelected = isSelected;
                  if(isSelected){
                      this.checkedDataList = []
                      this.tableList.forEach(item=>{
                          this.checkedDataList.push({
                              id:item.id,
                              code_id:item.codE_ID,
                              status:''
                          })
                          this.checkboxOption.selectedRowKeys.push(item.number)
                 
                      })
                    
                  }else{
                      this.checkboxOption.selectedRowKeys = []
                      this.checkedDataList = []
                  }          
              },
            },
            contextmenuBodyOptionMain:{
                contextmenus: [
                    {
                        type:'abnormal',
                        label:'审核通过'
                    },{
                        type:'error',
                        label:'审核未通过'
                    },
                    {
                        type:'abnormalMore',
                        label:'批量设为审核通过'
                    },{
                        type:'errorMore',
                        label:'批量设为审核未通过'
                    }
                ],
                afterMenuClick: ({ type, selectionRangeKeys, selectionRangeIndexes })=> {
                    this.afterRightMenu(type, selectionRangeKeys, selectionRangeIndexes)
                },
            },
            virtualScrollMain:{
                enable:this.enableVirtualScroll,
                scrolling: this.scrolling,
            },
            isAllSelected: false,
        }
    },
    watch:{
        enableVirtualScroll(newVal) {
            this.virtualScrollMain.enable = newVal;
        },
        tableList: {
        handler(newList) {
            if (this.isAllSelected) {
                this.autoSelectNewData(newList);
            }
        },
        deep: true
  },
    },
    computed:{
      columns() {
        let columns = []
        if(this.isOverview){
            columns.push({
                title:'状态',
                field:'outliersign',
                key:'outliersign',
                width: 80,
                renderBodyCell: ({ row, column, rowIndex }, h) => {
                    const status = row.outliersign;
                    if(status == '审核通过'){
                        return(
                            <el-tooltip class="item" effect="dark" content='审核通过' placement="top-start">
                                <i class="iconfont greenText ico">&#xe630;</i>
                            </el-tooltip>
                        )
                    }else if(status == '审核未通过'){
                        return(
                            <el-tooltip class="item" effect="dark" content='审核未通过' placement="top-start">
                                <i class="iconfont redText ico" style="font-size:18px">&#xe654;</i>
                            </el-tooltip>
                        )
                    }else if(status == '未审核'){
                        return(
                            <el-tooltip class="item" effect="dark" content='未审核' placement="top-start">
                                <i class="iconfont greyText ico">&#xe645;</i>
                            </el-tooltip>
                        )
                    }
                }
            })
        }else{
            columns.push({
                title:'状态',
                field:'outliersign',
                key:'outliersign',
                width: 80,
                type: "checkbox",
                renderBodyCell: ({ row, column, rowIndex }, h) => {
                    const status = row.outliersign;
                    if(status == '审核通过'){
                        return(
                            <el-tooltip class="item" effect="dark" content='审核通过' placement="top-start">
                                <i class="iconfont greenText ico">&#xe630;</i>
                            </el-tooltip>
                        )
                    }else if(status == '审核未通过'){
                        return(
                            <el-tooltip class="item" effect="dark" content='审核未通过' placement="top-start">
                                <i class="iconfont redText ico" style="font-size:18px">&#xe654;</i>
                            </el-tooltip>
                        )
                    }else if(status == '未审核'){
                        return(
                            <el-tooltip class="item" effect="dark" content='未审核' placement="top-start">
                                <i class="iconfont greyText ico">&#xe645;</i>
                            </el-tooltip>
                        )
                    }
                }
            })
        }
        columns.push ({
            field: "number",
            key: "number",
            operationColumn: false,
            title: "编号",
            width: 50,
        },{
            title:'测点名称',
            field:'pointName',
            key:'pointName',
            width:140,
        },{
            title:'观测时间',
            field:'watchTime',
            key:'watchTime',
            sortBy: "",
            width:190,
            renderBodyCell: ({ row, column, rowIndex }, h) => {
                return (
                    <div>
                        <i class="iconfont blueText smallIco">&#xe7ec;</i>
                        <span>{row.watchTime}</span>
                    </div>
                )
            }
        })
        // 动态表头部分
        if(this.isOverview || this.isEnv){
            columns.push({
                title:'分量名',
                field:'compname',
                key:'compname',
                width:100,
            },{
                title:'测值结果',
                field:'value',
                key:'value',
                sortBy: "",
                width:120,
                renderBodyCell:({ row, column, rowIndex }, h)=>{
                    const value = row.value;
                    const status = row.comP_outs
                    {
                        if(status == '正常'){
                            return (
                                <div class="result">   
                                <el-tooltip class="item" effect="dark" content='正常' placement="top-start">
                                    <i class="iconfont greenText">&#xe711;</i>
                                </el-tooltip>
                                    <span class="greenText">{value}</span>
                                </div>
                            );
                        }else if(status == '异常'){
                            return (
                                <div class="result">
                                    
                                    <el-tooltip class="item" effect="dark" content='异常' placement="top-start">
                                    <i class="iconfont yellowText">&#xe711;</i>
                                </el-tooltip>
                                    <span class="yellowText">{value}</span>
                                </div>
                            );
                        }else if(status == '错误'){
                            return (
                                <div class="result">
                                    <el-tooltip class="item" effect="dark" content='错误' placement="top-start">
                                        <i class="iconfont redText">&#xe711;</i>
                                </el-tooltip>
                                    <span class="redText">{value}</span>
                                </div>
                            );
                        }else{
                            return (
                                <div>
                                    <span>{value}</span>
                                </div>
                            );
                        }
                        
                    }
                }
            },{
                title:'审核类别',
                field:'measuresStatus',
                key:'measuresStatus',
                width:100,
            })
        }else{
            if(this.tableComPs.length > 0){
                this.tableComPs.forEach((item,index)=>{
                columns.push({
                    title:item,
                    field:item,
                    key:item,
                    sortBy: "",
                    width:120,
                    renderBodyCell:({ row, column, rowIndex }, h)=>{
                        const value = row[item];
                        const status = row[item + 'state']
                        {
                            if(status == '正常' || status == '正确'){
                            return (
                                <div class="result">   
                                <el-tooltip class="item" effect="dark" content='正常' placement="top-start">
                                    <i class="iconfont greenText">&#xe711;</i>
                                </el-tooltip>
                                    <span class="greenText">{value}</span>
                                </div>
                            );
                        }else if(status == '异常'){
                            return (
                                <div class="result">
                                    
                                    <el-tooltip class="item" effect="dark" content='异常' placement="top-start">
                                    <i class="iconfont yellowText">&#xe711;</i>
                                </el-tooltip>
                                    <span class="yellowText">{value}</span>
                                </div>
                            );
                        }else if(status == '错误'){
                            return (
                                <div class="result">
                                    <el-tooltip class="item" effect="dark" content='错误' placement="top-start">
                                        <i class="iconfont redText">&#xe711;</i>
                                </el-tooltip>
                                    <span class="redText">{value}</span>
                                </div>
                            );
                        }else{
                            return (
                                <div>
                                    <span>{value}</span>
                                </div>
                            );
                        }
                            
                        }
                        }
                    })
                })
            }
        }
        columns.push({
            title:'录入人员',
            field:'recordUser',
            key:'recordUser',
            width:140,
            renderBodyCell: ({ row, column, rowIndex }, h) => {
                return (
                    <div>
                        <i class="iconfont blueText smallIco" style="font-size:22px">&#xeb54;</i>
                        <span>{row.recordUser}</span>
                    </div>
                )
            }
        },{
            title:'审核人员',
            field:'treatmentUser',
            key:'treatmentUser',
            width:140,
            renderBodyCell: ({ row, column, rowIndex }, h) => {
                return (
                    <div>
                        <i class="iconfont blueText smallIco">&#xe60c;</i>
                        <span>{row.treatmentUser}</span>
                    </div>
                )
            }
        },{
            title:'备注',
            field:'remark',
            key:'remark',
            width:260,
            ellipsis: {
                showTitle: true,
            },
        })
        if(this.isChartFilter){
            columns.push({
                title:'操作',
                field:'operate',
                key:'operate',
                edit:false,
                width:120,
                renderBodyCell:({ row, column, rowIndex }, h)=>{
                return (
                    <el-button type="text" on-click={() => this.handleDelLinePoint(row)}>隐藏</el-button>
                );          
                }
            })
        }
        return columns;
      },
    },
    beforeDestroy() {
        if (this.timer) {
            clearTimeout(this.timer);
            this.timer = null;
        }
        this.isAllSelected = false;
    },
    methods:{
        autoSelectNewData(newList) {
            if (!this.isAllSelected) return;
            // 找出新添加的数据（不在当前选中列表中的）
            const newItems = newList.filter(item => 
            !this.checkedDataList.some(checked => checked.id === item.id)
            );
        
            newItems.forEach(item => {
            this.checkedDataList.push({
                id: item.id,
                code_id: item.codE_ID,
                status: ''
            });
            
            if (!this.checkboxOption.selectedRowKeys.includes(item.number)) {
                this.checkboxOption.selectedRowKeys.push(item.number);
            }
            });
        },
        sortChange(params){ 
            for(let i in params){
                if(i == 'watchTime'){
                    this.tableList.sort((a, b) => {
                        let val1 = a[i];
                        let val2 = b[i];
                        if (params[i] === "asc") {
                            return new Date(val1) - new Date(val2);
                        } else if (params[i] === "desc") {
                            return new Date(val2) - new Date(val1);
                        } else {
                            return 0;
                        }
                    });
                }
                
                if(params[i] != '' && i != 'watchTime'){
                this.tableList.sort((a, b) => {
                    if (params[i] === "asc") {
                        return a[i] - b[i];
                    } else if (params[i] === "desc") {
                        return b[i] - a[i];
                    } else {
                        return 0;
                    }
                });
                }
            }
        },
        afterRightMenu(type, selectionRangeKeys, selectionRangeIndexes) {
            const handleAction = (status, isMultiple = false) => {
                const _dataList = [];
                if (isMultiple) {
                // 批量操作
                if (this.checkedDataList.length === 0) {
                    this.$message.error('请先勾选需要操作的数据！');
                    return false;
                }
                
                const actionText = status === 1 ? '通过' : '未通过';
                this.$confirm(
                    `您当前已勾选 ${this.checkedDataList.length} 条数据，确定要将这些数据全部审核为${actionText}吗？`,
                    '批量审核',
                    { type: 'warning' }
                ).then(() => {
                    this.checkedDataList.forEach(item => {
                        _dataList.push({
                            id: item.id,
                            code_id: item.code_id,
                            status: status
                        });
                    });
                    this.$emit('updateValue', _dataList);
                    this.clearSelection();
                }).catch(() => {});
                
                } else {
                // 单条操作
                const data = this.tableList[selectionRangeKeys.startRowKey - 1];
                if (this.checkedDataList.length > 1) {
                    const actionText = status === 1 ? '通过' : '未通过';
                    this.$confirm(
                    `检测到您选择了多条数据，但此操作每次只能审核单条记录。您希望如何处理？`,
                    '审核',
                    {
                        type: 'warning',
                        confirmButtonText: '仅操作当前项',
                        cancelButtonText: '操作全部勾选项',
                    }
                    ).then(() => {
                    // 仅操作当前项
                    _dataList.push({
                        id: data.id,
                        code_id: data.code_id,
                        status: status
                    });
                    this.$emit('updateValue', _dataList);
                    this.clearSelection();
                    }).catch(() => {
                    // 操作全部勾选项
                    this.checkedDataList.forEach(item => {
                        _dataList.push({
                        id: item.id,
                        code_id: item.code_id,
                        status: status
                        });
                    });
                    this.$emit('updateValue', _dataList);
                    this.clearSelection();
                    });
                } else {
                    _dataList.push({
                        id: data.id,
                        code_id: data.code_id,
                        status: status
                    });
                    this.$emit('updateValue', _dataList);
                    this.clearSelection();
                }
                }
            };

            // 清理选择状态
            this.clearSelection = () => {
                this.checkboxOption.selectedRowKeys = [];
                this.checkedDataList = [];
            };

            const actionMap = {
                'abnormal': () => handleAction(1),
                'error': () => handleAction(2),
                'abnormalMore': () => handleAction(1, true),
                'errorMore': () => handleAction(2, true)
            };

                if (actionMap[type]) {
                    actionMap[type]();
                } else {
                    console.warn(`未知的操作类型: ${type}`);
                }
        },
        scrolling({
            startRowIndex,
            visibleStartIndex,
            visibleEndIndex,
            visibleAboveCount,
            visibleBelowCount,
        }) {
            if (this.timer) clearTimeout(this.timer)
            
            // 检测是否滚动到底部
            if(visibleBelowCount <= 0){
                this.timer = setTimeout(() => {
                    this.loadMoreData()
                }, 300)
            }else{
                clearTimeout(this.timer)
            }
        },
        
        loadMoreData(){
            this.$emit('load-more')
        },
        handleDelLinePoint(data){
            this.$confirm(`确认要将时间为 ${data.watchTime} 的数据隐藏?`,{
                type:'warning'
            }).then(() => {
                this.$emit('tableDataHide',data)
            }).catch(() => {}); 
        },
    }
})
</script>
<style scoped lang="scss">
::v-deep .ico{
    font-size: 20px !important;
    vertical-align: middle !important;
}
::v-deep .result{
    i{
        margin-right: 8px;
        font-size: 14px;
    }
}
</style>
